TextureMgr = {};
local referenceCount = {};

local function addReferenceCount(obj)
    if Utils.isNil(obj) then
        return ;
    end
    local key = obj.name;
    if referenceCount[key] then
        referenceCount[key] = referenceCount[key] + 1;
    else
        referenceCount[key] = 1;
    end
end

function TextureMgr:minusReferenceCount(obj)
    if Utils.isNil(obj) then
        return ;
    end
    local key = obj.name;
    if referenceCount[key] then
        referenceCount[key] = referenceCount[key] - 1;
        if referenceCount[key] == 0 then
            ResMgr:clearRes("Texture/"..key);
            referenceCount[key] = nil;
        end
    end
end

function TextureMgr:setSprite(sp,textureName)
    local sprite = nil;
    if Main.isUseEditorRes then
        sprite = AssetDatabase.LoadAssetAtPath("Assets/ExternalRes/Prefab/Texture/" .. textureName .. ".png", typeof(Sprite));
        if not sprite then
            sprite = AssetDatabase.LoadAssetAtPath("Assets/ExternalRes/Prefab/Texture/" .. textureName .. ".jpg", typeof(Sprite));
        end
        TimeMgr:delayFrame(1, function () sp.sprite = sprite end);--异步
    else
        local ab = ResMgr:getAB("Texture/" .. textureName);
        sprite = ResMgr.CMain:GetAssetObject(ab, textureName.."ToSprite");
        if sprite then
            TextureMgr:minusReferenceCount(sp.sprite);
            addReferenceCount(sprite);
            sp.sprite = sprite;
        else
            ResMgr.CMain:LoadAssetAsync(ab, textureName.."ToSprite", function (o)
                TextureMgr:minusReferenceCount(sp.sprite);
                addReferenceCount(o);
                sp.sprite = o;
            end, false);
        end
    end
end

function TextureMgr:setTexture(sp,textureName)
    local sprite = nil;
    if Main.isUseEditorRes then
        sprite = AssetDatabase.LoadAssetAtPath("Assets/ExternalRes/Prefab/Texture/" .. textureName .. ".png", typeof(Texture));
        if not sprite then
            sprite = AssetDatabase.LoadAssetAtPath("Assets/ExternalRes/Prefab/Texture/" .. textureName .. ".jpg", typeof(Texture));
        end
        TimeMgr:delayFrame(1, function () sp.texture = sprite end);--异步
    else
        local ab = ResMgr:getAB("Texture/" .. textureName);
        sprite = ResMgr.CMain:GetAssetObject(ab, textureName);
        if sprite then
            TextureMgr:minusReferenceCount(sp.texture);
            addReferenceCount(sprite);
            sp.texture = sprite;
        else
            ResMgr.CMain:LoadAssetAsync(ab, textureName, function (o)
                TextureMgr:minusReferenceCount(sp.texture);
                addReferenceCount(o);
                sp.texture = o;
            end, false);
        end
    end
end